package com.cloud.school.app.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

/**
 * @ClassName: FileUtils
 * @Description: 文件操作工具类
 */
public final class FileUtils {

    private static final String point = ".";

    private static volatile String serverUrl;

    private static volatile String fileUploadPath;

    public static void setPath(String serverIpPort, String filePath) {
        serverUrl = serverIpPort;
        fileUploadPath = filePath;
    }

    public static boolean deleteFile(String filePath) {
        File file = new File(System.getProperty("user.dir") + File.separator + fileUploadPath + File.separator + filePath.substring(filePath.lastIndexOf("/")));
        if (file.exists()) {
            return file.delete();
        }
        return true;
    }

    private static String getUploadFileSuffix(MultipartFile uploadFile) {
        String fileName = uploadFile.getOriginalFilename();
        int index = fileName.lastIndexOf(point);
        if (index <= 0) {
            return fileName;
        } else {
            return fileName.substring(index + 1);
        }
    }

    /**
     * @param uploadFile
     * @Title: uploadFile
     * @Description: 上传附件的基础方法
     * @return: java.lang.String
     */
    public static String uploadFile(MultipartFile uploadFile) {
        String targetPath = fileUploadPath + File.separator;
        // 获取上传文件的后缀名
        String fileSuffix = FileUtils.getUploadFileSuffix(uploadFile);
        try {
            // 检查需要保存文件的路径是否存在不存在则创建
            File targetFile = new File(System.getProperty("user.dir") + File.separator + targetPath);
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            }
            // 文件名
            String fileName = UUID.randomUUID().toString().replace("-", "") + point + fileSuffix;
            // 保存文件
            File newFile = new File(targetFile.getAbsoluteFile() + File.separator + fileName);
            uploadFile.transferTo(newFile);        // 将上传的文件转移到给定的目标文件
            return serverUrl + "/" + fileUploadPath.replaceAll("\\\\", "/") + "/" + fileName;
        } catch (Exception e) {
            return "";
        }
    }
}